package com.example.wanbaqian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.wanbaqian.R;
import com.example.wanbaqian.bean.UserInfoBean;
import com.google.gson.Gson;
import com.example.wanbaqian.base.BaseActivity;
import com.example.wanbaqian.config.CommonValue;
import com.example.wanbaqian.base.HttpCallback;
import com.example.wanbaqian.config.HttpURL;
import com.example.wanbaqian.bean.Info;
import com.example.wanbaqian.utils.BaseUtils;
import com.example.wanbaqian.utils.GetJsonUtils;
import com.example.wanbaqian.utils.HttpUtils;
import com.example.wanbaqian.utils.SPUtils;
import com.example.wanbaqian.widget.CustomEditText;
import com.example.wanbaqian.widget.TimeButton;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.tongdun.android.shell.FMAgent;

public class LoginActivity extends BaseActivity implements HttpCallback {
    @BindView(R.id.login_usernameEt)
    CustomEditText loginUsernameEt;
    @BindView(R.id.login_passwordEt)
    CustomEditText loginPasswordEt;
    @BindView(R.id.btn_sendcode)
    TimeButton timeButton;

    @BindView(R.id.l_login)
    Button lLogin;

    @BindView(R.id.img_back)
    ImageView mBack;

    @BindView(R.id.txt_title)
    TextView mTitle;
    String username;

    private long startTime;

    private long loginTime;

    private long pageFinsh;

    private static final String TAG = "LoginActivity";
    private Bundle bundle;
    private String IMEI = "";
    private List<Map<String, String>> contactList = new ArrayList<>();

    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        bundle = getIntent().getExtras();
        if (null == bundle && SPUtils.contains(mContext, CommonValue.userInfo)) {
            openActivity(HomeActivity.class);
            finish();
        }
        setStatusBarColorInFragment();
        setListenter();
//        lReg.setText(BaseUtils.setTextColor(mContext, "还没账号,立即注册", 5, 9, R.color.colorBackground));
//        Glide.with(mContext).load(R.mipmap.ic_launcher).transform(new GlideRoundTransform(mContext)).into(lLogo);
        IMEI = BaseUtils.getIMEI(mContext);
        //2017年10月9日09:57:01   小米应用市场发布初步猜测是此处获取不到联系人导致，暂时解决办法，不传联系人
        contactList = BaseUtils.readContact(mContext);
        sendContact();
    }

    @Override
    protected void initDate() {
    }

    private void setListenter() {
        mBack.setImageResource(R.mipmap.ic_dl_close);
        mTitle.setText("登录");
        mTitle.setTextColor(getResources().getColor(R.color.white));
    }


    @OnClick({R.id.btn_sendcode, R.id.l_login})
    public void onClick(View view) {
        username = loginUsernameEt.getText().toString();
        switch (view.getId()) {
            case R.id.btn_sendcode:
                sendAuthcode = true;
                if (BaseUtils.isMobileNO(loginUsernameEt.getText().toString())) {
                    timeButton.statsend();
                    loginPasswordEt.setText("");
                    loginPasswordEt.requestFocus();
                    sendCode(username);
                } else {
                    showToast("请输入正确的手机号码");
                }
                break;
            case R.id.l_login:

                String password = loginPasswordEt.getText().toString();
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                    showToast("请填写用户名或者密码");
                    return;
                } else if(password.length()<6){
                    showToast("请输入正确验证码");
                }else{
                    setLogin(username, password);
                }
                break;
        }
    }

    boolean sendAuthcode = false;

    /**
     * 获取验证码
     *
     * @param phone
     */
    private void sendCode(String phone) {
        String[] key = {"accessid", "user_mobile", "sms_type"};
        String[] value = {CommonValue.accessid_value, phone, "0"};
        HttpUtils.getInstance().postKey(GetJsonUtils.getInstance().
                getRequest(HttpURL.SMS_SEND, mContext, key, value), mContext, CommonValue.REQUEST_CODE3, this);
    }

    /**
     * 登录操作
     *
     * @param password
     */
    private void setLogin(String username, String password) {
        btnUnUse();
        //TODO 需要获取同盾blackBox传给后台
        String blackBox = FMAgent.onEvent(LoginActivity.this);
        Log.e("TD_JAVA", "setLogin_blackBox: " + blackBox);
        //这次给他存一下，下次先实时取，取不到？用本地的
        SPUtils.put(this,"tdJava",""+blackBox);
        String registrationID = JPushInterface.getRegistrationID(mContext);
        Log.e(TAG, "setLogin登录获取极光Id registrationID : "+registrationID);
        startTime = System.currentTimeMillis();
        HttpUtils.getInstance().postKey(GetJsonUtils.getInstance()
                        .getRequest(HttpURL.USER_LOGIN, mContext,
                                new String[]
                                        {
                                        "accessid",
                                        "user_mobile",
                                        "valicode",
                                        "device_version",
                                        "longitude",
                                        "latitude",
                                        "device_id",
                                        "device_os",
                                        "device_name",
                                        "device_detail",
                                        "registration_id",
                                        "black_box"
                                        }
                                , new Object[]{
                                        CommonValue.accessid_value,
                                        username,
                                        password,
                                        BaseUtils.geVersionCode(mContext),
                                        "",
                                        "",
                                        IMEI,
                                        android.os.Build.VERSION.SDK_INT,
                                        android.os.Build.MANUFACTURER,
                                        "",
                                        ""+registrationID,
                                        ""+blackBox
                                })
                , mContext, CommonValue.REQUEST_CODE1, this);

//        Log.e("LOGIN_SU", "开始登陆时间: " + startTime);

    }

    @Override
    public void onSuccess(String content, Info info, int requestCode) {
        btnUse();
        switch (requestCode) {
            case CommonValue.REQUEST_CODE1:
                loginTime = System.currentTimeMillis();
                Log.e("LOGIN_SU", "登陆借口花费时间: "+(loginTime - startTime));
                Log.e("LOGIN_SU", "登录成功系统时间: " + loginTime);

                SPUtils.setUserInfo(mContext, content);
                Log.e("LOGIN_SU", "content : " + content);

//                Log.e("LOGIN_SU", "登录成功存储数据onSuccess: " + content);

//                openActivity(HomeActivity.class);

                UserInfoBean userInfo = SPUtils.getUserInfo(mContext);
                //2017年9月19日17:23:51 业务逻辑，同盾暴露给后台，后台置为-1，禁止前端登录
                String loginStatus = userInfo.getLoginStatus();
                if("-1".equals(loginStatus)){
                    showToast("暂不符合登录要求");
                }else{
                    Intent intent = new Intent(this, HomeActivity.class);
                    startActivity(intent);
                    finish();

                }


                break;
            case CommonValue.REQUEST_CODE2:
//                pageFinsh =  System.currentTimeMillis();
//                Log.e("LOGIN_SU", "page: " +pageFinsh );
//                Log.e("LOGIN_SU", "onSuccess: "+(pageFinsh - startTime));
//                openActivity(HomeActivity.class);
//                finish();
                break;
            case CommonValue.REQUEST_CODE3:
                sendAuthcode = true;
                break;

        }
    }

    private void sendContact() {
        if(null == contactList || contactList.size()<=0){
            return;
        }

        HttpUtils.getInstance().post(
                GetJsonUtils.getInstance().getRequest(HttpURL.AUTH_CONTACTS,
                        mContext,
                new String[]
                        {
                                "accessid",
                                "contacts"
                        },
                new String[]
                        {
                                SPUtils.getAccessid(mContext) + "",
                                new Gson().toJson(contactList.toString())
                        }),
                null,
                CommonValue.REQUEST_CODE2,
                LoginActivity.this);
    }

    @Override
    public void onCacheSuccess(String content, Info info, int requestCode) {
        btnUse();
    }

    @Override
    public void onError(Info info, int requestCode) {
        btnUse();
        switch (requestCode) {
            case CommonValue.REQUEST_CODE1:
                Log.e(TAG, "loginOnError: " + info.toString());
                showToast(info.getMsg());
                break;
            case CommonValue.REQUEST_CODE2:
//                pageFinsh =  System.currentTimeMillis();
//                Log.e("LOGIN_SU", "page: " +pageFinsh );
//                openActivity(HomeActivity.class);
//
//                finish();
                break;
            case CommonValue.REQUEST_CODE3:
                timeButton.stop();
                sendAuthcode = false;
                showToast(info.getMsg());
                break;
        }

    }


    /**
     * 登录按钮置灰，艹，不重要的按钮别让傻逼双击
     */
    private void btnUnUse(){
        if(null != lLogin){
            lLogin.setEnabled(false);
            lLogin.setAlpha(0.3f);
        }
    }

    private void btnUse(){
        if(null != lLogin){
            lLogin.setEnabled(true);
            lLogin.setAlpha(1f);
        }
    }

}
